(function(window,undefined){
	var Landmark = {};
	window.Landmark = window.Landmark || Landmark;
	
	var addUserLocation = function(_landmark_info){
		var landmarkStarSelector =  '#selectList a.favoritePlace';
		var user_id = sessionStorage.getItem('user_id');
		
		$.ajax({
			type:'post',
			url:ajaxURL+'location.php?action=addUserLocation',
			data:{user_id:user_id, title:_landmark_info._landmark_name , combine_code:_landmark_info._combine_code},
			success:function(result){
				console.log(result);
				Landmark.userLocationBlock();
			}
		});
	};
	
	var delUserLocation = function(_combine_code,that){
		var _user_id = sessionStorage.getItem('user_id');
		$.ajax({
			type:'post',
			url:ajaxURL+'location.php?action=delUserLocation',
			data:{user_id:_user_id, combine_code:_combine_code},
			success:function(result){
				console.log(result);
				that.remove();
				$('.landmarkWrap li[data-combine_code='+_combine_code+'] .favoritePlace').removeClass('on');
			}
		});
	};
	
	Landmark.userLocationBlock = function(){
		var _selector='div.savePlace ul';
		var user_id = sessionStorage.getItem('user_id');
		
		$.ajax({
			type:'post',
			url:ajaxURL+'location.php?action=loadUserLocation',
			data:{user_id:user_id},
			dataType:'json',
			success:function(result){
				console.log(result);
				$(_selector).empty();
				$.each(result,function(){
					$(_selector).append('<li><a data-combine_code="'+this.combine_code+'" href="#">'+this.title+'</a></li>');
					
				});
				
				
			}
		});
		
		$('.editBtn').toggle(function(event) {
			event.preventDefault();
			$(_selector+' li').addClass('delete');
			$('li.delete a').off('click').on('click',function(event){
				event.preventDefault();
				
				
				var _combine_code=$(this).data('combine_code');
				delUserLocation(_combine_code,$(this));
			});
			$(this).html('완료');
		}, function(event) {
			event.preventDefault();
			$(_selector+' li').removeClass('delete');
			$(this).html('편집');
		});
		
	};
	
	
	var _callback,_landmark_code,level0,level1,_cntType; /*rootblock callback*/
	/*페이지가 변경/시작될떄 호출*/
	Landmark.init = function(__callback,__cntType){
		if(!__callback){
			alert('Category 콜백 초기화가 필요합니다.');
			return ;
		}
		if(!__cntType){
			_cntType = "storeCnt";
			return ;
		}
		_cntType = __cntType;
		_callback = __callback;
		
		_landmark_code = sessionStorage.getItem('landmark_code');
		if(!_landmark_code){
			sessionStorage.setItem('landmark_name',"모란역");
			sessionStorage.setItem('landmark_code','GGSNMR');
		}
		level0=_landmark_code.substring( 0,2 );
		level1=_landmark_code.substring( 2,4 );
	};
	
	Landmark.rootBlock = function(){
		Model.loadRootLandmark(function(result){
			var info = '', leftBlockSelector = '#selectList > .stateWrap > ul';
			
			/*template*/
			$(leftBlockSelector).empty();
			$.each(result, function() {
				info += '<li data-landmark_code = "' + this.landmark_code + '"><a href="#">' + this.name + '</a></li>';
			});
			$(leftBlockSelector).append(info);
			
			if (_landmark_code) {
				$('#selectList > .stateWrap > ul > li,#selectList > .localWrap > ul > li,#selectList > .landmarkWrap > ul > li').removeClass('on');
				Landmark.parentBlock(level0, 'default');
				$('#selectList > .stateWrap > ul > li[data-landmark_code=' + level0 + ']').addClass('on');
			}

			/*click listener*/
			$('#selectList > .stateWrap > ul > li').off('click').on('click', function(event) {
				event.preventDefault();

				$('#selectList > .stateWrap > ul > li').removeClass('on');
				$(this).addClass('on');

				Landmark.parentBlock($(this).data('landmark_code'));
				$('#selectList > .landmarkWrap > ul').empty();
			});
		});
	};
	
	
	var Model = {
		loadRootLandmark : function(__callback){
			$.ajax({
				type:"post",
				url:ajaxURL + "location.php?action=loadRootLandmark",
				data:{},
				dataType:"json",
				success:function(result){
					__callback(result);
				}
			});
		}
	};
	
	Landmark.parentBlock = function(__parent0,_type){
		if(!__parent0){
			alert("파라없음");
		}
		
		$.ajax({
			type:"post",
			url:ajaxURL + "location.php?action=loadParentLandmark",
			data:{code:__parent0},
			dataType:"json",
			success:function(result){
				/*template*/
				var _selector0 = $('#selectList > .localWrap > ul');
				var info = '';
				
				_selector0.empty();
				$.each(result,function(){
					info += '<li data-landmark_code='+this.landmark_code+'><a href ="#">'+this.name+'</a></li>';
				});
				_selector0.append(info);
				
				
				
				if(_landmark_code && _type=='default'){
					$('#selectList > .localWrap > ul > li[data-landmark_code='+level1+']').addClass('on');
					Landmark.childBlock(level0,level1);
					$('#selectList > .landmarkWrap > .title > span').html($('#selectList > .localWrap > ul > li[data-landmark_code='+level1+'].on').html());

				}
				
				/*click listener*/
				var _selector1 = $('#selectList > .localWrap > ul > li > a');
				_selector1.off('click').on('click',function(event){
					event.preventDefault();
					
					_selector1.parent().removeClass('on');
					$(this).parent().addClass('on');
					$('#selectList > .landmarkWrap > .title > span').html($(this).html());
					Landmark.childBlock(__parent0,$(this).parent().data('landmark_code'));
				});
			}
		});
	};
	
	Landmark.childBlock = function(__parent0,__parent1){
		if(!__parent0){
		}
		if(!__parent1){	
		}
		var _user_id = sessionStorage.getItem('user_id');
		$.ajax({
			type:"post",
			url:ajaxURL + "location.php?action=loadChildLandmark",
			data:{parent0:__parent0,parent1:__parent1,user_id:_user_id},
			dataType:"json",
			success:function(result){
				$('#selectList > .landmarkWrap > ul').empty();
				
				/*template*/
				var info = '';
				$.each(result,function(){
					var options = {
						limitLangth : 12,
						content : this.name
					};
					info += '<li data-combine_code='+this.combine_code+'><a class="favoritePlace '+this.is_landmark_favorite+'"></a><a class="landmark_name" data-landmark_name="'+this.landmark_name+'" href ="#">'+UIAssist.textHandler(options)+'</a></li>';
				});
				$('#selectList > .landmarkWrap > ul').append(info);
				
				
				if(_landmark_code){
					$('#selectList > .landmarkWrap > ul > li[data-combine_code='+_landmark_code+']').addClass('on');
					var _landmark_name=$('#selectList > .landmarkWrap > ul > .on a:nth(1)').html();
					// $('#selectLoc a:nth(0)').html(_landmark_name);
				}
				
				/*카테고리 이름 클릭*/
				var _selector0 = '#selectList > .landmarkWrap > ul > li > .landmark_name';
				$(_selector0).off('click').on('click',function(event){
					event.preventDefault();
					
					$(_selector0).parent().removeClass('on');
					$(this).parent().addClass('on');
					
					$('#selectLoc .opener').toggleClass('on');
					$("#selectList").slideToggle("fast");
					
					Landmark.titleBlock($(this).html());
					
					/*session*/
					_landmark_code = $(this).parent().data('combine_code');
					var is_landmark_favorite='';
					if($(this).hasClass('on')){
						is_landmark_favorite='on';
					}
					var _landmark_name=$(this).data('landmark_name');
					
					sessionStorage.setItem('landmark_name',_landmark_name);
					sessionStorage.setItem('landmark_code',_landmark_code);
					_callback();
					
					Category.loadCategoryCount(sessionStorage.getItem('landmark_code'),_cntType);
					addRecentlyLandmark(_landmark_code+'+false+'+$(this).html(),is_landmark_favorite);
					Landmark.recentlyLandmarkBlock();
				});
				
				/*카테고리 별 클릭*/
				var _selector1 = '#selectList > .landmarkWrap > ul > li > .favoritePlace';
				$(_selector1).off('click').on('click',function(event){
					event.preventDefault();
					
					if(confirm("자주가는지역으로 등록하시겠습니까?")){
						$(this).addClass('on');
						var _combine_code=$(this).parent().data('combine_code');
						var _landmark_name=$(this).parent().find('.landmark_name').html();
						var _landmark_info={_combine_code:_combine_code,_landmark_name:_landmark_name};
						addUserLocation(_landmark_info);
					}
				})
			}
		});
	};
	
	Landmark.footerLandmarkBlock = function(){
		Model.loadRootLandmark(function(result){
			$("#bottomLoc a").click(function() {
				scrollTo(0,0);
				$('#selectLoc .opener').toggleClass('on');
				$("#selectList").slideToggle("fast");
			});
		});
	};
	
	
	Landmark.titleBlock = function(landmarkTitle){
		if(!landmarkTitle){
			landmarkTitle = sessionStorage.getItem('landmark_name');
		}
		$('#selectLoc > a.location').html(UIAssist.textHandler({
			limitLangth : 8,
			content : landmarkTitle
		}));
	};
	
	Landmark.nearLandmarkSearch = function(__callback,__cntType){
		var isGeolocation = sessionStorage.getItem('is_geolocation');
		if(isGeolocation == 'on'){
			return;
		}
		navigator.geolocation.getCurrentPosition(function(position){
			var _lat = position.coords.latitude, _lng = position.coords.longitude;
			$.ajax({
				type:"post",
				url:ajaxURL + "location.php?action=nearLandmarkSearch",
				async:false,
				data:{lat: _lat,lng: _lng},
				dataType:"json",
				success:function(result){
					console.log(result);
					sessionStorage.setItem('is_geolocation','on');
					sessionStorage.setItem('landmark_name',result.name);
					sessionStorage.setItem('landmark_code',result.combine_code);
					location.reload();
				}
			});
		}),function(){
			alert(FAIL_LOAD_CURRENT_LOCATION);
		};
	};
	
	/*최근검색지역*/
	/*recently 구조 : {랜드마크코드번호+자주가는지역등록여부+랜드마크이름}*/
	Landmark.recentlyLandmarkBlock = function(){
		var _temp0 = localStorage.getItem('recently'), _temp1 = [], _recently = [];
		
		if(_temp0){
			_temp1 = _temp0.split('@');
		}
		
		for(var i=0;i<_temp1.length;i++){
			_recently[i] = _temp1[i].split('+');
		}
		
		$('#recentsearch > ul').empty();
		var info = '';
		$.each(_recently.reverse(),function(){
			console.log(this);
			if(this[1] == "true"){
				info += '<li data-landmark_code="'+this[0]+'"><a data-landmark_name="'+this[2]+'" class="favoritePlace on">자주가는 지역</a><a href="#">'+this[2]+'</a></li>';
			} else if(this[1] == "false"){
				info += '<li data-landmark_code="'+this[0]+'"><a data-landmark_name="'+this[2]+'" class="favoritePlace">자주가는 지역</a><a href="#">'+this[2]+'</a><div class="pop"><span>자주가는 지역으로 추가해보세요.</span></div></li>';
			}
		});
		
		$('#recentsearch > ul').append(info);
		
		/*listener*/
		$('#recentsearch > ul > li').off('click').on('click',function(event){
			event.preventDefault();
			var _landmark_name=$('#selectList > .landmarkWrap > ul > .on a').html();
			_landmark_name = $(this).children().data('landmark_name');
			sessionStorage.setItem('landmark_name',_landmark_name);
			_landmark_code = $(this).data('landmark_code');
			sessionStorage.setItem('landmark_code',_landmark_code);
			
			location.href = 'index.php';
		});
	};
	
	var addRecentlyLandmark = function(__str,_is_landmark_favorite){
		var _recently = localStorage.getItem('recently');
		var MAX = 5, temp0 = [], temp1 = [], _gap = 0 ,_result = '';/*MAX : 최근 선택지역 최대 리스트 값*/
		
		if(!_recently){/*초기값 예외처리*/
			localStorage.setItem('recently',__str);
			return;
		}else{
			/*값이 같으면 추가 못하게 막음*/
			temp1 = __str.split('+');
			if(_recently.indexOf(temp1[0]) != -1 ){
				return;
			}
			
			_recently = _recently+ '@' +__str;
		}
		
		/*MAX 값으로 배열 유지*/
		temp0 = _recently.split('@');
		_gap = temp0.length - MAX;
		while(_gap > 0){
			temp0.shift();
			_gap = _gap - 1;
		}
		
		/*배열을 다시 문자열으로 변경*/
		for(var i =0; i < temp0.length;i++){
			if(i == temp0.length - 1){/*마지막에 들어가는 값에는 @이가 없어야됨*/
				_result += temp0[i];
			}else {
				_result += temp0[i]+'@';
			}
		}
		
		localStorage.setItem('recently',_result);
	};
})(window);
